var uploadAndshow = document.getElementById("uploadAndshow");

uploadAndshow.addEventListener("click",handleUploadAndshow );




var tableBody;
var pagination;
var rows ;
var exportButton;
var rowsPerPage;
var Data;
var currentPage=1;

const userType=localStorage.getItem('userType');

//向后端获取数据的调用函数
function getInfo(url) {
  fetch(url, {
    method: 'GET',
  })
    .then(response => {
      if (response.ok) {
        return response.json(); // 解析响应数据为 JSON
      } else {
        throw new Error('网络错误');
      }
    })
    .then(data => {
      Data=data;
      console.log(data)
      show(Data);
    })
    .catch(error => {
      console.error('获取数据时出现错误:', error);
    });
}

//向后端发送数据。再获取数据
function SendAndGet(url,formData) {
  fetch(url, {
    method: 'POST' ,// Keeping the method as POST
    body:formData
  })
    .then(response => {
      if (response.ok) {
        return response.json(); // Parse the response data as JSON
      } else {
        throw new Error('网络错误');
      }
    })
    .then(data => {
      // Handle the retrieved data
      console.log('后端返回的数据:', data);
      Data=data;

      show(Data);
      // Perform further operations or display data as needed
    })
    .catch(error => {
      // Handle errors
      console.error('获取数据时出现错误:', error);
    });
}

function SendAndDelete(url,formData) {
  fetch(url, {
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST' ,// Keeping the method as POST
    body:formData
  })
      .then(response => {
        if (response.ok) {
          return response.json(); // Parse the response data as JSON
        } else {
          throw new Error('网络错误');
        }
      })
      .then(data => {
        // Handle the retrieved data
        console.log('后端返回的数据:', data);
        Data=data;

        show(Data);
        // Perform further operations or display data as needed
      })
      .catch(error => {
        // Handle errors
        console.error('获取数据时出现错误:', error);
      });
}

// //展示灾情信息部分
// const data = [
//   { id:'数据1', col2: '数据A',  col3: '数据B', col4: '数据A', col5: '数据A', col6: '数据A', col7: '数据A', col8: '数据A', col9: '数据A'},
//   { id: '数据2', col2: '数据B', col3: '数据A', col4: '数据A', col5: '数据A', col6: '数据A', col7: '数据A', col8: '数据A', col9: '数据A' },
//   
//   // 添加更多数据项
// ];

function show(data){
    // 显示初始页
    
    displayPagination(data);
    displayTable();
    
}


function handleUploadAndshow() {
  var main = document.getElementsByClassName('main')[0];
  if(userType=='visitor'){
    main.innerHTML = 
  '<button class="btn btn-primary BatchExport" id="BatchExport">批量导出</button>'+
  '<div class="table-responsive">' +
  '<table class="table table-bordered table-hover" id="disasterform">' +
  ' <thead>' +
  ' <tr>' +
  ' <th></th>' +
  ' <th class="specialFont">灾情码</th>' +
  ' <th class="specialFont">位置</th>' +
  ' <th class="specialFont">日期</th>' +
  ' <th class="specialFont">来源</th>' +
  ' <th class="specialFont">数据载体</th>' +
  ' <th class="specialFont">分类</th>' +
  ' <th class="specialFont">灾情指标</th>' +
  ' <th class="specialFont">描述</th>' +
  ' </tr>' +
  ' </thead>' +
  ' <tbody id="tableBody">' +
  ' </tbody>' +
  '</table>' +
  '</div>' +
  '<div class="table-controls">' +
  ' <nav>' +
  '   <div class="pagination" id="pagination"></div>' +
  ' </nav>' +
  '</div>';
  var form =document.getElementById('disasterform');
  form.style.top= '0px';
  }else{
    main.innerHTML = '<form action="/file-upload" class="dropzone" id="myDropzone"></form>' +
  '<button class="btn btn-primary BatchExport" id="BatchExport">批量导出</button>'+
  '<div class="table-responsive">' +
  '<table class="table table-bordered table-hover" id="disasterform">' +
  ' <thead>' +
  ' <tr>' +
  ' <th></th>' +
  ' <th class="specialFont">灾情码</th>' +
  ' <th class="specialFont">位置</th>' +
  ' <th class="specialFont">日期</th>' +
  ' <th class="specialFont">来源</th>' +
  ' <th class="specialFont">数据载体</th>' +
  ' <th class="specialFont">分类</th>' +
  ' <th class="specialFont">灾情指标</th>' +
  ' <th class="specialFont">描述</th>' +
  ' </tr>' +
  ' </thead>' +
  ' <tbody id="tableBody">' +
  ' </tbody>' +
  '</table>' +
  '</div>' +
  '<div class="table-controls">' +
  ' <nav>' +
  '   <div class="pagination" id="pagination"></div>' +
  ' </nav>' +
  '</div>';
  }
  

      tableBody = document.getElementById('tableBody');
      pagination = document.getElementById('pagination');
      rows = tableBody.getElementsByTagName('tr');
      exportButton = document.getElementById('BatchExport');
      rowsPerPage = 6; // 每页显示的行数
      getInfo('/data/show')




    // Configuration for Dropzone
    if(userType!='visitor'){
      Dropzone.autoDiscover = false;

    // Initialize Dropzone
    var myDropzone = new Dropzone("#myDropzone", {
      maxFilesize: 10, // 文件最大10MB
      addRemoveLinks: true, // 添加删除链接
      dictDefaultMessage: "拖放文件至此或点击上传", // 默认提示消息
      init: function () {
        this.on("complete", function (file) {
          var formData = new FormData();
          formData.append('file', file);
          console.log(111);
          SendAndGet('/data/upload',formData);
          // 当文件上传完成时触发
          // if (file.status === 'success') {
          //     // 使用 Ajax 将文件数据发送到后端
          //
          // }else {
          //     console.log(222);
          // }
        });

      }
    });
    // Update maxFiles if needed
    myDropzone.options.maxFiles = 10;

  
}

  exportButton.addEventListener('click', function () {
    const tableBody = document.getElementById('tableBody'); // 获取表格内容元素
    const rows = tableBody.getElementsByTagName('tr'); // 获取所有行元素
    const selectedRows = [];

    // 遍历表格行以查找被勾选的行
    for (var i = 0; i < rows.length; i++) {
      const checkbox = rows[i].querySelector('input[type="checkbox"]');
      if (checkbox.checked) {
        // 如果勾选框被勾选，将对应行的 ID 存入数组
        const rowID = Data[i].id; // 假设每行有 data-id 属性存储 ID
        selectedRows.push(rowID);
      }
    }
    const selectedData=selectedRows.map(id => {
      return Data.find(row=>row.id===id);
    });
    jsonData=JSON.stringify(selectedData);
    exportToExcel(selectedData);
  });


  tableBody.addEventListener('click', function(event) {
    // 检查点击的元素是否为按钮

    if (event.target.classList.contains('deleteButton')) {
      // 找到所点击的按钮所在的行
      const row = event.target.closest('tr');

      // 获取所在行的索引
      const rowIndex = Array.from(row.parentNode.children).indexOf(row);


      const convertedData={
        id:Data[rowIndex].id,
      }
      console.log("shouw:",Data[rowIndex].id);
      jsonData=JSON.stringify(convertedData);

      SendAndDelete('/data/deleteData',jsonData);
    }
  });

}






function displayTable() {
  tableBody.innerHTML = '';
  const start = (currentPage - 1) * rowsPerPage;
  const end = currentPage * rowsPerPage;
  const paginatedData = Data.slice(start, end);

  paginatedData.forEach(item => {
    const row = document.createElement('tr');
    const checkboxCell = document.createElement('td');
    
    const deleteCell = document.createElement('td');
    const checkbox = document.createElement('input');
    const deleteButton = document.createElement('button');
    deleteButton.textContent = "删除";
    deleteButton.classList.add("deleteButton");
    checkbox.type = 'checkbox';

    checkbox.addEventListener('change', function () {

    });

    checkboxCell.appendChild(checkbox);
    row.appendChild(checkboxCell);

    const columns = [ 'code', 'location', 'dating', 'source', 'carrier', 'directory', 'indexing', 'description'];
    columns.forEach(column => {
      const cell = document.createElement('td');
      cell.textContent = item[column];
      row.appendChild(cell);
    });

    deleteCell.appendChild(deleteButton);
    row.appendChild(deleteCell);

    tableBody.appendChild(row);
    if (userType=='visitor'){
      deleteButton.disabled=true;
      deleteButton.style.display='none';
    }
  });
  const pageInfo=document.getElementById('pageInfo');
  pageInfo.innerHTML =`第 ${currentPage} 页`;
}

function displayPagination(data) {
  // 清空分页导航
  pagination.innerHTML = "";

  // 计算总页数
  const pageCount = Math.ceil(data.length / rowsPerPage);

  // 创建“前一页”按钮
  const prevButton = document.createElement('button');
  prevButton.id = "prevButton";
  prevButton.innerText = "前一页";
  // prevButton.disabled = currentPage === 1; // 当在第一页时禁用按钮
  prevButton.addEventListener('click', function () {
    if (currentPage > 1){
      currentPage--;
      displayTable();
    } 
  });
  pagination.appendChild(prevButton);

  // 显示当前页码和总页数
  const pageInfo = document.createElement('span');
  pageInfo.id="pageInfo";
  pageInfo.innerText = `第 ${currentPage} 页`;
  pagination.appendChild(pageInfo);

  // 创建“后一页”按钮
  const nextButton = document.createElement('button');
  nextButton.id="nextButton";
  nextButton.innerText = "后一页";
  nextButton.disabled = currentPage === pageCount; // 当在最后一页时禁用按钮
  nextButton.addEventListener('click', function () {
    if (currentPage < pageCount) {
      currentPage++;
      displayTable();
    }
  });
  pagination.appendChild(nextButton);

  const pageNum = document.createElement('span');
  pageNum.id="pageNum";
  pageNum.innerText = `共 ${pageCount} 页`;
  pagination.appendChild(pageNum);
  
}


function exportToExcel(data) {
  const workbook = XLSX.utils.book_new();
  console.log(data);
  const worksheet = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

  // 将 workbook 转换为 Excel 数据
  const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

  // 创建一个 Blob 对象
  const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });

  // 设定文件名并创建下载链接
  const fileName = 'exported_data.xlsx';
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = fileName;

  // 模拟点击下载链接
  link.click();
}
//删除灾情信息功能

// 添加点击事件监听器







